<template>
  <div class="app-container">

    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="工单状态:" prop="workOrderStatus">
          <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态">
            <el-option v-for="item in dict.type.work_order_status" :label="item.label"
                       :value="item.value" :key="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车牌号/车架号:" prop="carNoVinNo">
          <el-input v-model="queryParams.carNoVinNo" clearable placeholder="请输入车牌号/车架号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车辆产权:">
          <el-select filterable v-model="queryParams.propertyRightId" clearable placeholder="请选择车辆产权"
                     style="width: 100%">

            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId" />

          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆归属:">
          <el-select filterable v-model="queryParams.ascriptionId" clearable placeholder="请选择车辆归属"
                     style="width: 100%">

            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId" />

          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="批次号:" prop="flowBusinessId">
          <el-input v-model="queryParams.flowBusinessId" clearable placeholder="请输入批次号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="品牌/车系/车型:">
          <linkage-select @changeNode="linkageChange" v-model="linkageList" placeholder="请选择品牌/车系/车型"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="产品类型:" prop="contractType">
          <el-select v-model="queryParams.contractType" placeholder="请选择产品类型" style="width: 100%;">
            <el-option v-for="item in dict.type.quota_rent_type" :key="item.value" :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>
      </el-col>
      <!--      <el-col :span="6">-->
      <!--        <el-form-item label="合同禀议编号:" prop="contractReportNumber">-->
      <!--          <el-input v-model="queryParams.contractReportNumber" clearable placeholder="请输入合同禀议编号"></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col :span="6">-->
      <!--        <el-form-item label="采购禀议编号:" prop="procurementReportNumber">-->
      <!--          <el-input v-model="queryParams.procurementReportNumber" clearable placeholder="请输入采购禀议编号"></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="6">
        <el-form-item label="上次年检到期日:" prop="lastTime">
          <el-date-picker v-model="time" type="daterange" range-separator="至" start-placeholder="开始日期"
                          end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="timeChange"
                          style="width: 100%;">
          </el-date-picker>

        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="工单创建时间:">
          <el-date-picker v-model="createTime" type="daterange" range-separator="至" start-placeholder="开始日期"
                          end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="createTimeChange"
                          style="width: 100%;">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchContent>
    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <e-button type="primary" size="mini"
                  v-hasPermi="['inspect:inspectList:add']" @click="handleAdd">新增
        </e-button>
        <e-button type="primary" size="mini"
                  v-if="queryParams.workOrderStatus == 1 || queryParams.workOrderStatus == 5"
                  v-hasPermi="['inspect:inspectList:batch']" @click="unifyCheck"
                  :disabled="!idList.length >0">批量处理
        </e-button>
      </div>

      <table-page :loading="loading" :dataList="dataList" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @setSizeCurrent="getList" :isSelect="true" border
                  @selectionChange="selectionChange">
        <template slot="tableColAc">
          <el-table-column label="操作" align="center" fixed="left" width="100">
            <template slot-scope="{row}">
              <el-button size="mini" type="text" @click="viewOpen(row, 'view')"
                         v-hasPermi="['inspect:inspectList:view']"
                         v-if="row.workOrderStatus !== 1">查看
              </el-button>

              <el-button size="mini" type="text" v-hasPermi="['inspect:inspectList:handle']"
                         v-if="row.workOrderStatus == 1 || row.workOrderStatus == 5"
                         @click="handleWork(row)">处理
              </el-button>

            </template>
          </el-table-column>

        </template>

        <template slot="tableCol">
          <el-table-column align="center" label="年检工单编号" prop="workOrderCode" show-overflow-tooltip
                           min-width="180"/>
          <el-table-column align="center" label="批次号" prop="flowBusinessId" show-overflow-tooltip
                           min-width="180"/>
          <el-table-column align="center" label="车牌号" min-width="100" prop="carNo">

          </el-table-column>
          <el-table-column align="center" label="车架号" show-overflow-tooltip min-width="180" prop="vinNo"/>

          <el-table-column align="center" label="品牌/车型" show-overflow-tooltip width="280">
            <template slot-scope="{row}">
              {{ row.brandName }}{{ row.modelName ? '/' + row.modelName : '' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="车辆产权" show-overflow-tooltip min-width="160"
                           prop="propertyRightName"/>
          <el-table-column align="center" label="车辆归属" show-overflow-tooltip min-width="160" prop="ascription"/>
          <el-table-column align="center" label="车辆运营" show-overflow-tooltip min-width="120"
                           prop="operationsName"/>
          <el-table-column align="center" label="车辆大区" show-overflow-tooltip min-width="160">
            <template #default="{row}">
              <span v-if="row.region">{{ row.region }} </span>

            </template>
          </el-table-column>

          <el-table-column align="center" label="工单类型" width="96">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.work_order_type, row.workOrderType) }}工单
            </template>

          </el-table-column>
          <el-table-column align="center" label="客户名称" width="160" show-overflow-tooltip prop="customerName"/>
          <el-table-column align="center" label="产品类型" width="100">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.quota_rent_type, row.contractType) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="车辆性质" width="100">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.car_nature, row.carNature) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="车辆状态" width="160">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.car_business_type, row.businessType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年检状态" width="100">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.inspection_status, row.inspectionStatus) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="工单状态" width="100">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.work_order_status, row.workOrderStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="审批状态" show-overflow-tooltip min-width="140" prop="expenseStatus" />
          <el-table-column align="center" label="订单编号" show-overflow-tooltip width="200"
                           prop="orderCode"/>
          <el-table-column align="center" label="上次年检时间" min-width="160" prop="inspectionLastTime">
            <template slot-scope="{row}">
              {{ row.lastInspectionTime ? $dayjs(row.lastInspectionTime).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="年检到期日" min-width="160">
            <template slot-scope="{row}">
              {{ row.inspectionLastTime ? $dayjs(row.inspectionLastTime).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="处理人" width="120" prop="processedByName"/>

          <el-table-column align="center" label="处理时间" width="140">
            <template slot-scope="{row}">
              {{ row.processedByTime ? $dayjs(row.processedByTime).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="工单创建时间" width="140">
            <template slot-scope="{row}">
              {{ row.createTime ? $dayjs(row.createTime).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>
        </template>
      </table-page>
    </div>

    <addDialog ref="refAddDialog" @change="handleAddChange"/>
  </div>
</template>

<script>
import {
  getDataList, getInspectionDetails, getInspectionLists, checkInspection

} from "@/api/cwgd/inspectApi.js";
import SearchContent from "@/components/SearchContent/index.vue";
import addDialog from './components/addDialog.vue'
import {
  getToken
} from "@/utils/auth";

import LinkageSelect from "../../components/linkageSelect";
import CitySelect from "../../components/citySelect.vue"
import { listDept } from "@/api/system/dept";
export default {

  name: "InspectList",

  dicts: ['car_business_type', 'work_order_type', 'quota_rent_type',
    'car_nature', 'inspection_status', 'work_order_status'],
  components: {
    LinkageSelect, CitySelect,
    SearchContent,
    addDialog,
  },
  computed: {},
  data() {
    return {
      idList: [],
      linkageList: [],
      citySelection: [],
      // 遮罩层
      loading: false,

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNoVinNo: "",
        procurementReportNumber: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        contractReportNumber: "",
        belongCityName: "",
        workOrderStatus: "1",
        customerName: "",
        workOrderType: "9",

        createStartTime: "",
        createEndTime: "",
        startTime: "",
        endTime: "",
        propertyRightId: "",
        ascriptionId: "",
        inspectionLastTime:"",
        flowBusinessId:""
      },

      total: 0,
      dataList: [],
      createTime: [],
      time: [],
      companyOriginList: [],


    };
  },
  created() {
    this.getList();
    this.getCompanyOrigin();
  },
  methods: {
    getCompanyOrigin() {
      listDept({
        deptType: "2", //组织类型（1部门 2公司）
        regionId: null, //所在城市（省市区id）
      }).then((res) => {
        this.companyOriginList = res.data;
      });
    },
    //新增
    handleAdd() {
      this.$refs.refAddDialog.handleOpen(9)
    },

    handleAddChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    citySelectionChange(val) {
      if (val.length > 0) {
        const nodes = Array.from(val, item => ({
          value: item.value,
          label: item.label,
          pv: item.parent.value,
          pl: item.parent.label
        }))
        this.queryParams.belongCityName = nodes[0].label
        this.citySelection = [nodes[0].pv, nodes[0].value]

      } else {
        this.citySelection = val

        this.queryParams.belongCityName = ""
      }

    },

    createTimeChange(val) {

      if (val) {
        this.queryParams.createStartTime = val[0]
        this.queryParams.createEndTime = val[1]
      } else {
        this.queryParams.createStartTime = ""
        this.queryParams.createEndTime = ""
      }
    },
    timeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
      } else {
        this.queryParams.startTime = ""
        this.queryParams.endTime = ""
      }

    },
    handleSelectionChange(val) {
    },
    linkageChange(val) {
      this.linkageList = val
      if (val) {
        this.queryParams.brandName = val[0] ? val[0].name : ''
        this.queryParams.seriesName = val[1] ? val[1].name : ''
        this.queryParams.modelName = val[2] ? val[2].name : ''
      } else {
        this.queryParams.brandName = ""
        this.queryParams.seriesName = ""
        this.queryParams.modelName = ""
      }
      this.$forceUpdate()
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      getDataList(this.queryParams).then(res => {
        if (res.code == "200") {
          const {
            rows,
            total
          } = res
          this.dataList = rows
          this.total = total
          this.loading = false;
        }
      }).catch(() => {
        this.loading = false;
      })
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        carNoVinNo: "",
        procurementReportNumber: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        contractReportNumber: "",
        belongCityName: "",
        workOrderStatus: "1",
        customerName: "",
        workOrderType: "9",

        createStartTime: "",
        createEndTime: "",
        startTime: "",
        endTime: "",
        propertyRightId: "",
        ascriptionId: "",
        inspectionLastTime:"",
        flowBusinessId:""
      }
      this.createTime = []
      this.time = []
      this.citySelection = []
      this.linkageList = []
      this.getList();
    },

    viewOpen(row, type) {
      this._toPage({
        path: "/cwgd/inspectDetails",
        name: 'InspectDetails',
        query: {
          id: row.id,
          carId: row.carId,
          businessDataId: row.businessDataId,
          types: 'view',
          flowId: row?.flowId || null,
        }
      })

    },

    // 批量选择
    selectionChange(val) {

      this.idList = val

    },

    /** 批量处理校验 */
    unifyCheck() {
      if (this.idList.length > 0) {
        let bidstr = this.idList.map(v => {
          if (v.businessDataId) {
            return v.businessDataId
          }
        }).join(',')

        let wid = this.idList.map(v => {
          return v.id
        }).join(',')
        let ids = this.idList.map(a => {
          return a.id
        })
        checkInspection({idList: ids, workOrderType: '9'}).then(res => {
          if (res.code === 200) {
            this._toPage({
              path: "/cwgd/inspectDetailsList",
              name: 'InspectDetailsList',
              query: {
                // businessDataId: bidstr,
                id: wid,
                types: 'edit'
              }
            })
          }
        })
      }


    },

    handleWork(row) {
      if (!row.businessDataId) {
        this._toPage({
          path: "/cwgd/inspectDetails",
          name: 'InspectDetails',
          query: {
            id: row.id,
            carId: row.carId,
            types: 'edit',
            flowId: row?.flowId || null,
          }
        })
      } else {
        this._toPage({
          path: "/cwgd/inspectDetails",
          name: 'InspectDetails',
          query: {
            id: row.id,
            carId: row.carId,
            businessDataId: row.businessDataId,
            types: 'edit',
            flowId: row?.flowId || null,
          }
        })
      }


    },

  }
};
</script>

<style lang="scss" scoped>
.el-form {
  padding: 18px 20px;
  padding-bottom: 8px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 16px;

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }

  ::v-deep .el-form-item__label {
    font-size: 14px;
    font-family: 400;
  }
}
</style>
